package model

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ BankIconModel = (*customBankIconModel)(nil)

type (
	// BankIconModel is an interface to be customized, add more methods here,
	// and implement the added methods in customBankIconModel.
	BankIconModel interface {
		bankIconModel
		FindOneByName(ctx context.Context, name string) (*BankIcon, error)
	}

	customBankIconModel struct {
		*defaultBankIconModel
	}
)

// NewBankIconModel returns a model for the database table.
func NewBankIconModel(conn sqlx.SqlConn, c cache.CacheConf) BankIconModel {
	return &customBankIconModel{
		defaultBankIconModel: newBankIconModel(conn, c),
	}
}

func (m *defaultBankIconModel) FindOneByName(ctx context.Context, name string) (*BankIcon, error) {
	publicBankIconNameKey := fmt.Sprintf("%s%v", cachePublicBankIconNamePrefix, name)
	var resp BankIcon
	err := m.QueryRowCtx(ctx, &resp, publicBankIconNameKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
		query := fmt.Sprintf("select %s from %s where name = $1 limit 1", bankIconRows, m.table)
		return conn.QueryRowCtx(ctx, v, query, name)
	})
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}
